#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
import os

import logging
logging.getLogger().setLevel(logging.INFO)
#logging.error("++++++++++++ 1 cwd = %s, path = %s" % (os.getcwd(), os.environ["Path"] ))
from google.appengine.api import images


ProjectPath = os.path.dirname(os.getcwd())
sys.path.insert(0, ProjectPath)
sys.path.insert(0, os.path.join(ProjectPath, 'common'))
sys.path.insert(0, os.path.join(ProjectPath, 'database'))

#logging.error("++++++++++++ 2 cwd = %s, path = %s" % (os.getcwd(), os.environ["Path"] ))

import wsgiref.handlers

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from database import googledatabase
from database import function_user
from database import function_admin

import databasefunction
import commonfunction

import friend.frienddatabase as frienddatabase
import like.likedatabase as likedatabase


#template.register_template_library('templates.my_filter_tag')



PAGE_SIZE = 20

class CUserInfoPage(commonfunction.CBasePage):
    def get(self):
        TemplateValues = self.GetBaseDefaultTemplateValue()
        
        UserInfo = function_user.GetOneUserInfo(commonfunction.GetUserLoginID())
        TemplateValues.update( { 'UserInfo':UserInfo, } )
	
        TemplateFilePath = self.GetRightLanguageHtmlFilePath('userinfo')

        self.response.out.write(template.render(TemplateFilePath, TemplateValues))
	

    def post(self):
        LoginID = commonfunction.GetUserLoginID()
        NickName = self.request.get('NickName')
        Gender = int(self.request.get('Gender'))
        Country = self.request.get('Country').strip()
#        logging.error("-----------CUserInfoPage AllowFriend = %s", self.request.get('AllowFriend'))
        AllowFriend = int(self.request.get('AllowFriend'))
        PublicType = int(self.request.get('PublicType'))
        
        #检查昵称是否已存在
        if 0 < len(NickName):
            if databasefunction.CheckNickNameIsExist(NickName, LoginID):
                TemplateValues = self.GetBaseDefaultTemplateValue()
                
                if self.GetTheSessionLanguage() == 'zh-cn':
            	    TemplateValues.update( { 'Error':u'昵称已存在', } )
                else:
            	    TemplateValues.update( { 'Error':u'Nick name already exist.', } )
    
                TemplateValues.update( { 'BackUrl':'/userinfo', } )
                TemplateFilePath = self.GetRightLanguageHtmlFilePath('error')
                self.response.out.write(template.render(TemplateFilePath, TemplateValues))
                return

        UserInfo = databasefunction.GetOneUserInfo(LoginID)
        if UserInfo is None:
            UserInfo = function_user.AddCurrentUserToUserTable("zh-cn")
        if UserInfo is None:
            self.redirect('/userinfo')
            return

#        logging.error("-----------------CUserInfoPage post UserInfo = %s" %(UserInfo.__dict__) )
        PhotoData = self.request.get("Photo")
        if PhotoData:
            UserInfo.HavePhoto = True
#            UserInfo.Photo = db.Blob( images.resize(PhotoData, 80, 80) )
            UserInfo.Photo = db.Blob( PhotoData )

        if UserInfo.NickName is None or 1 > len(UserInfo.NickName):
            AdminConfig = function_admin.GetAdminConfig()
            UserInfo.Integral += AdminConfig.IntegralRegister

        UserInfo.Gender = Gender
        UserInfo.Country = Country
        UserInfo.Address = self.request.get('Address')
        UserInfo.Latitude = float(self.request.get('Latitude'))
        UserInfo.Longitude = float(self.request.get('Longitude'))
        UserInfo.GeoBoxes = function_user.GetGeoBoxList(UserInfo.Latitude, UserInfo.Longitude)
        UserInfo.AllowFriend = AllowFriend
        UserInfo.PublicType = PublicType
        function_user.SetOneUserInfo(UserInfo)

        self.redirect('/userinfo')


    def head(self):
        pass

class CUserPhotoPage(commonfunction.CBasePage):
    def get(self):
        Item = self.request.get('item', '')
        UserInfo = function_user.GetOneUserInfo(Item)
        Photo = None
        if UserInfo:
            if UserInfo.HavePhoto:
                Photo = UserInfo.Photo

        self.response.headers['Content-Type'] = 'image/jpeg'
        if Photo:
            self.response.out.write(Photo)
        else:
            self.redirect('/images/defaultphoto.jpg')


class CUserShowPage(commonfunction.CBasePage):
    def get(self):
        TemplateValues = self.GetDefaultTemplateValue()
        Item = self.request.get('item', '')
        CurUserInfo = databasefunction.GetOneUserInfo(commonfunction.GetUserLoginName())
        ShowUserInfo = databasefunction.GetOneUserInfo(Item)
        if ShowUserInfo == None:
            ShowUserInfo = databasefunction.GetOneUserInfoFromNickName(Item)

        if ShowUserInfo == None:
            self.redirect('/')
            return

        TimeDelta = self.GetTheSessionTimeDelta()
        #该用户最新 微博
        UserBlogs, UserPrePage, UserNextPage = databasefunction.GetOneUserMicroblogRecord(ShowUserInfo.LoginName, PAGE_SIZE, TimeDelta)
        TemplateValues.update( { 'UserBlogs':UserBlogs, } )

        #该用户最新 收藏
        UserCollects, UserPrePage, UserNextPage = databasefunction.GetOneUserCollectRecord(ShowUserInfo.LoginName, PAGE_SIZE, TimeDelta)
        TemplateValues.update( { 'UserCollects':UserCollects, } )

        #该用户最新 喜爱
        UserLikes, UserPrePage, UserNextPage = likedatabase.GetOneUserLikeRecord(ShowUserInfo.LoginName, PAGE_SIZE, TimeDelta)
        TemplateValues.update( { 'UserLikes':UserLikes, } )

        #该用户的朋友
        UserFriends, UserPrePage, UserNextPage = frienddatabase.GetOneUserFriendRecord(ShowUserInfo.LoginName, 1, PAGE_SIZE, TimeDelta)
        TemplateValues.update( { 'UserFriends':UserFriends, } )

        if CurUserInfo == None:
            TemplateValues.update( { 'NotIsMyFriend':False, } )
        elif CurUserInfo.LoginName == ShowUserInfo.LoginName:
            TemplateValues.update( { 'NotIsMyFriend':False, } )
        else:
            FriendItem = frienddatabase.GetOneMyFriend(ShowUserInfo.LoginName)
            if FriendItem:
#                logging.error( "FriendItem type = %s, dict = %s, dir = %s" % (type(FriendItem), FriendItem.__dict__, dir(FriendItem)) )
#                self.response.out.write( "FriendItem.FriendName = %s, FriendItem.LoginName = %s" % (FriendItem.FriendName, FriendItem.LoginName) )
                TemplateValues.update( { 'NotIsMyFriend':False, } )
            else:
                TemplateValues.update( { 'NotIsMyFriend':True, } )

#        CanShow = False
#        if ShowUserInfo.PublicType == 2:
#            if self.GetTheSessionLanguage() == 'zh-cn':
#        	TemplateValues.update( { 'Error':u'该用户信息未公开', } )
#            else:
#        	TemplateValues.update( { 'Error':u'The user\'s information is not public.', } )
        	
#        elif ShowUserInfo.PublicType == 1:
#            if CurUserInfo:
#                if CurUserInfo.LoginName == ShowUserInfo.LoginName:
#                    CanShow = True
#                elif databasefunction.UserIsFriend(ShowUserInfo.LoginName, CurUserInfo.LoginName):
#                    CanShow = True
#                else:
#                    if self.GetTheSessionLanguage() == 'zh-cn':
#                        TemplateValues.update( { 'Error':u'该用户信息只有朋友才允许查看', } )
#                    else:
#                        TemplateValues.update( { 'Error':u'Only friend can look the user\'s information.', } )
#            else:
#                if self.GetTheSessionLanguage() == 'zh-cn':
#                    TemplateValues.update( { 'Error':u'该用户信息只有朋友才允许查看', } )
#                else:
#                    TemplateValues.update( { 'Error':u'Only friend can look the user\'s information.', } )
                    
#        elif ShowUserInfo.PublicType == 0:         
#            CanShow = True
        
#        if CanShow:
#            TemplateValues.update( { 'ShowUserInfo':ShowUserInfo, } )
#            TemplateFilePath = self.GetRightLanguageHtmlFilePath('usershow')
#            self.response.out.write(template.render(TemplateFilePath, TemplateValues))
#        else:
#            TemplateValues.update( { 'BackUrl':'/', } )
#            TemplateFilePath = self.GetRightLanguageHtmlFilePath('error')
#            self.response.out.write(template.render(TemplateFilePath, TemplateValues))
            
#---------------------------------------- 以下为不显示错误框的------------------------------
        CanShow = False
        if ShowUserInfo.PublicType == 1:
            if CurUserInfo:
                if CurUserInfo.LoginName == ShowUserInfo.LoginName:
                    CanShow = True
                elif databasefunction.UserIsFriend(ShowUserInfo.LoginName, CurUserInfo.LoginName):
                    CanShow = True
        elif ShowUserInfo.PublicType == 0:         
            CanShow = True
        TemplateValues.update( { 'CanShow':CanShow, } )
        
        TemplateValues.update( { 'ShowUserInfo':ShowUserInfo, } )
        TemplateFilePath = self.GetRightLanguageHtmlFilePath('usershow')
        self.response.out.write(template.render(TemplateFilePath, TemplateValues))




class CUserCheckRPCPage(commonfunction.CBasePage):
    def get(self):
        NickName = self.request.get('nickname')
#        logging.error("----------CCheckUserRPCPage 1 NickName = %s" % (NickName))
#        NickName = simplejson.loads(NickName)
#        logging.error("----------CCheckUserRPCPage 2 NickName = %s" % (NickName))
        if NickName == None:
            JsonStr = simplejson.dumps(-1)
        else:
            IsExist = databasefunction.CheckNickNameIsExist(NickName, commonfunction.GetUserLoginName())
            if IsExist:
                JsonStr = simplejson.dumps(1)
            else:
                JsonStr = simplejson.dumps(0)
            
        self.response.out.write(JsonStr)



def main():
    application = webapp.WSGIApplication([
                                        ('/userinfo', CUserInfoPage),
                                        ('/userphoto', CUserPhotoPage),
                                        ('/usershow', CUserShowPage), 
                                        ('/user_check_rpc', CUserCheckRPCPage), 
                                        ],
                                        debug=True)
    
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()


